--- 模块功能：MQTT客户端处理框架
-- @author openLuat
-- @module mqtt.mqttTask
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "misc"
require "mqtt"
require "mqttInMsgThird"
require "nvm"
require "logGenerator"
require "mqttOutMsgThird"
require "thirdPartyHttpRequest"
-- 初始化nvm获取配置参数
nvm.init("config.lua", true)
-- 参数初始化
local ready, slen = false, string.len
local mqttHost, mqttPort, groupId, clientId, uname, pwd, proTopic, drillTopic,
      ackTopic, configTopic, merchantNo, longitude, latitude, serialNumber,
      scenarioId = nvm.get("thirdConfig")[1], nvm.get("thirdConfig")[2],
                   nvm.get("thirdConfig")[3], nvm.get("thirdConfig")[4],
                   nvm.get("thirdConfig")[5], nvm.get("thirdConfig")[6],
                   nvm.get("thirdConfig")[7], nvm.get("thirdConfig")[8],
                   nvm.get("thirdConfig")[9], nvm.get("thirdConfig")[10],
                   nvm.get("thirdConfig")[12], nvm.get("longitude"),
                   nvm.get("latitude"), nvm.get("info")[1],
                   nvm.get("thirdConfig")[13]
-- 组装主题列表
local function assembleTopictThird()
    local topicList = {}
    log.info("configTopic:", configTopic, "proTopic:", proTopic, "drillTopic:",
             drillTopic)
    topicList[drillTopic] = 2
    topicList[configTopic] = 2
    topicList[proTopic] = 2
    return topicList
end

--- MQTT连接是否处于激活状态
-- @return 激活状态返回true，非激活状态返回false
-- @usage mqttTask.isReady()
function isReady() return ready end

-- 启动MQTT客户端任务
function startMQTTClientThird()
    sys.taskInit(function()
        local retryConnectCnt, retryStartDevCnt = 0, 0
        while true do
            if not socket.isReady() then
                retryConnectCnt = 0
                -- 等待网络环境准备就绪，超时时间是5分钟   20240426 change from 300000 to 10000
                sys.waitUntil("IP_READY_IND", 10000)
                retryStartDevCnt = retryStartDevCnt + 1
            end
            if socket.isReady() then
                log.info("pwd:", pwd, "useName:", uname)
                local transport, hostAndPort =
                    string.split(string.split(mqttHost, "//")[1], ":")[1],
                    string.split(mqttHost, "//")[2]
                retryStartDevCnt = 0
                -- 创建一个MQTT客户端
                local mqttClient = mqtt.client(clientId, 60, uname, pwd)
                -- 阻塞执行MQTT CONNECT动作，直至成功
                -- 如果使用ssl连接，打开mqttClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"})，根据自己的需求配置
                -- mqttClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"})
                if mqttClient:connect(hostAndPort, mqttPort, transport) then
                    retryConnectCnt = 0
                    ready = true
                    -- 订阅主题
                    if mqttClient:subscribe(assembleTopictThird()) then
                        log.info("第三方平台连接成功")
                        -- 循环处理接收和发送的数据
                        while true do
                            if not mqttInMsgThird.proc(mqttClient) then
                                log.error(
                                    "mqttTaskTHird.mqttInMsgThird.proc error")
                                break
                            end
                            if not mqttOutMsgThird.proc(mqttClient) then
                                log.error(
                                    "mqttTaskThird.mqttOutMsgThird.proc error")
                                break
                            end
                        end
                    end
                    ready = false
                else
                    log.info("retryConnectCnt:", retryConnectCnt)
                    if retryConnectCnt == 1 then
                        local params = {
                            merchantNo = merchantNo,
                            serialNumber = serialNumber,
                            scenarioId = scenarioId,
                            longitude = longitude,
                            latitude = latitude
                        }
                        thirdPartyHttpRequest.RegistrationAndChange(params)
                    end
                    retryConnectCnt = retryConnectCnt + 1
                end
                -- 断开MQTT连接
                mqttClient:disconnect()
                if retryConnectCnt >= 5 then
                    link.shut()
                    retryConnectCnt = 0
                    -- 更改注册信息

                end
                sys.wait(500)
            else
                -- 进入飞行模式，20秒之后，退出飞行模式
                net.switchFly(true)
                sys.wait(20000)
                net.switchFly(false)
            end
            if retryStartDevCnt >= 6 then -- 20240426 change from 7 to 6
                retryStartDevCnt = 0
                sys.restart("重启设备！")
            end
        end
    end)
end
